package leetcodecompetition.D359AC;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: Siantar
 * @Date: 2023-08-20-11:23
 * @Description: 1.0
 */
public class T6467 {
    public int longestEqualSubarray(List<Integer> nums, int k) {
        int n = nums.size() + 1;
        int res = 0;
        LinkedList<Integer>[] ls = new LinkedList[n];
        int[] ld = new int[n];
        for (int i = 0; i < n; i++) {
            ls[i] = new LinkedList<>();
        }
        for (int i = 0; i < n - 1; i++) {
            int num = nums.get(i);
            if (ls[num].isEmpty()) {
                ls[num].addLast(i);
            } else if(ls[num].size()==1){
                if (ld[num] + i - ls[num].getLast() - 1 > k) {
                    ls[num].pollFirst();
                }else {
                    ld[num] += i - ls[num].getLast() - 1;
                }
                ls[num].addLast(i);
            }else {
                if (ld[num] + i - ls[num].getLast() - 1 > k) {
                    int a = ls[num].pollFirst();
                    int b = ls[num].getFirst();
                    ld[num] -= b - a - 1;
                }
                ld[num] += i - ls[num].getLast() - 1;
                ls[num].addLast(i);
            }
            res = Math.max(res, ls[num].size());
        }
        return res;
    }
}
